
const baseURI = 'https://hw.hwjjy.cn/employees.php';   //测试域名
//const baseURI = 'https://ceshi.hwjjy.cn/employees.php';   //测试域名

class BaseModel {
  constructor(props = {}) {
    // mock api
    this.baseURI = baseURI;  //url 域名
    this.url = props.url;  //url 接口
    this.needAjaxLoading = props.needAjaxLoading;  //局部加载
    this.method = props.method || 'POST';  //提交方式
    this.dataType = props.dataType || 'json';  //数据类型
    this.header = {}  //头部
    this.loadingText = props.loadingText || '';
    this.needAuth = false; // 接口是否需要登录鉴权
  }
  fetch(params = {}, complete = null) {
    const token = wx.getStorageSync('token'); // mock userinfo, 需要从用户态中获取
    const _model = this;
    const authorize = wx.getStorageSync("authorize"); // 授权

    return new Promise((resolve, reject) => {
      if (this.needAjaxLoading) {
        wx.showLoading({
          title: this.loadingText || '',
          mask: true
        });
      }
      if (this.needAuth && authorize=="") { // 接口需要鉴权且没有登录态token
        wx.navigateTo({
          url: '/pages/login/login'
        })
        wx.hideLoading();
        reject('auth');
      } else {
        wx.request({
          url: `${this.baseURI}/${this.url}`,
          data: { ...params, key: token},
          header: this.header,
          method: this.method,
          dataType: this.dataType,
          success({ data, statusCode }) {
            if (statusCode == 200) { // wx request 请求成功
              if (data.code == 0) { // 业务参数0为成功
                resolve(data)
              } else if (data.code == 400) { // 账号被禁用, 清除登录态, 跳转登录页
               if (!disableTimer) {
               wx.showToast({
               title: data.msg || '账号被禁用',
               icon: 'none',
               mask: true
               })
               disableTimer = setTimeout(() => {
               wx.removeStorageSync(authorize);
               wx.redirectTo({ url: '/pages/login/login' });
               disableTimer = null;
               }, 1500);
               }
               }
              reject(data) // 业务参数失败
            }
            reject(statusCode) // ajax请求失败
          },
          fail: reject,
          complete: function () {
            wx.hideLoading();
            complete && complete();
          }
        })
      }
    });
  }
}

export default BaseModel